import re

import ntdef
import slurm

from histdef import hists, histsets, hist_colfilters

import fill

from cutdef import cuts, cutsets

import textable

import dafit

import fit

channel_latex = r'$\Upsilon(5S)\toX\pi^0\pi^0$'

expnos = 'e000043 e000053 e000067 e000069 e000071 e000073'.split()

def expno_runno_from_path(path):
    rx = r'e[0-9]{6}'
    try:
        expno = re.search(rx, path).group(0)
    except AttributeError:
        raise ValueError("Cannot find an experiment number in path `{0}'".format(path))

    rx = r'r[0-9]{6}'
    try:
        runno = re.search(rx, path).group(0)
    except AttributeError:
        raise ValueError("Cannot find a run number in path `{0}'".format(path))

    return expno, runno


def generic_mc_ofname(tokens):
    tag = tokens[1]    
    stream = tokens[2]
    exp = int(tokens[4].split('r')[0][1:])

    return "generic_mc_exp{0}s{1}_{2}.h5".format(exp, stream, tag)

def ypipi_filename(expno, runno):
    return "ypipi-e{0:06d}r{1:06d}-b20090127_0910.h5".format(expno, runno)

def data_ofname(tokens):
    raise NotImplementedError


def scatter(x, y, **kwargs):
    from matplotlib import pyplot

    pyplot.figure(figsize=(8,6))

    pyplot.axes((0.175, 0.15, 0.8, 0.72))

    if 'xlabel' in kwargs:
        pyplot.xlabel(kwargs['xlabel'])
        del kwargs['xlabel']

    if 'ylabel' in kwargs:
        pyplot.ylabel(kwargs['ylabel'])
        del kwargs['ylabel']
    
    if 'xlim' in kwargs:
        pyplot.xlim(kwargs['xlim'])
        del kwargs['xlim']

    if 'ylim' in kwargs:
        pyplot.ylim(kwargs['ylim'])
        del kwargs['ylim']

    if 'title' in kwargs:
        pyplot.title(kwargs['title'])
        del kwargs['title']
        
    if 'fmt' in kwargs:
        fmt = kwargs['fmt']
        del kwargs['fmt']
    else:
        fmt = 'k.'

    if 'out' in kwargs:
        out = kwargs['out']
        del kwargs['out']
    else:
        out = 'scatter.png'

    pyplot.plot(x, y, fmt, **kwargs)

    pyplot.savefig(out)

    return out
